package com.yzk.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzk.train.business.entity.TrainCarriage;
import com.yzk.train.business.entity.TrainCarriageExample;
import com.yzk.train.business.enums.SeatColEnum;
import com.yzk.train.business.mapper.TrainCarriageMapper;
import com.yzk.train.business.request.TrainCarriageQueryReq;
import com.yzk.train.business.request.TrainCarriageSaveReq;
import com.yzk.train.business.response.TrainCarriageQueryResp;
import com.yzk.train.common.exception.BusinessException;
import com.yzk.train.common.exception.ExceptionEnum;
import com.yzk.train.common.response.PageResp;
import com.yzk.train.common.utils.SnowUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TrainCarriageService {

    @Resource
    private TrainCarriageMapper trainCarriageMapper;

    /**
     * 保存 / 更新 火车车厢
     * @param req
     */
    public String save(TrainCarriageSaveReq req) {
        DateTime now = DateTime.now();

        // 根据排数，计算列数和总座位数
        List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType());
        req.setColCount(seatColEnums.size());
        req.setSeatCount(seatColEnums.size() * req.getRowCount());

        TrainCarriage trainCarriage = BeanUtil.copyProperties(req, TrainCarriage.class);
        trainCarriage.setUpdateTime(now);
        if (ObjectUtil.isNull(trainCarriage.getId())) {

            // 保存之前，先校验唯一键是否存在，厢序
            TrainCarriage trainCarriageDB = selectByUnique(req.getTrainCode(), req.getIndex());
            if (ObjectUtil.isNotEmpty(trainCarriageDB)) {
                throw new BusinessException(ExceptionEnum.BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR);
            }

            trainCarriage.setId(SnowUtil.getSnowflakeNextId());
            trainCarriage.setCreateTime(now);
            trainCarriageMapper.insert(trainCarriage);
            return "保存成功";
        } else {
            trainCarriageMapper.updateByPrimaryKeySelective(trainCarriage);
            return "编辑成功";
        }
    }

    /**
     * 查询火车车厢列表
     * @param req
     */
    public PageResp<TrainCarriageQueryResp> queryList(TrainCarriageQueryReq req) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("train_code asc, `index` asc");
        // 如果有车次编号，则按照车次编码查询
        if (ObjectUtil.isNotNull(req.getTrainCode())) {
            trainCarriageExample.createCriteria().andTrainCodeEqualTo(req.getTrainCode());
        }
        // 使用分页插件
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<TrainCarriage> trainCarriages = trainCarriageMapper.selectByExample(trainCarriageExample);
        // 使用 PageInfo 包装查询结果
        PageInfo<TrainCarriage> pageInfo = new PageInfo<>(trainCarriages);
        // 转换为 PageResp
        List<TrainCarriageQueryResp> list = BeanUtil.copyToList(trainCarriages, TrainCarriageQueryResp.class);
        return new PageResp<>(pageInfo.getTotal(), list);
    }

    /**
     * 根据ID删除火车车厢
     * @param id
     */
    public void delete(Long id) {
        trainCarriageMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据车次编号查询车厢列表
     * @param trainCode
     * @return
     */
    public List<TrainCarriage> selectByTrainCode(String trainCode) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("`index` asc");
        trainCarriageExample.createCriteria().andTrainCodeEqualTo(trainCode);
        return trainCarriageMapper.selectByExample(trainCarriageExample);
    }

    /**
     * 校验唯一键
     * @param trainCode 车次编码
     * @param index     厢序
     * @return
     */
    private TrainCarriage selectByUnique(String trainCode, Integer index) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andIndexEqualTo(index);
        List<TrainCarriage> list = trainCarriageMapper.selectByExample(trainCarriageExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

}
